package sany.iec.utils;

import lombok.extern.slf4j.Slf4j;
import net.objecthunter.exp4j.Expression;
import net.objecthunter.exp4j.ExpressionBuilder;
import sany.iec.config.GlobalVariable;

/**
 * @Author 托马斯
 * @Date 2025/7/6 20:12
 * @Description FormulaCalculationUtil
 */
@Slf4j
public class FormulaCalculationUtil {

    /**
     * 根据公式计算结果
     *
     * @param tableName : 表名
     * @param formula   : 公式
     */
    public static Float getFormulaResult(String tableName, String formula) {
        String s = formula;
        try {
            for (String key : GlobalVariable.GLOBAL_MAP.keySet()) {
                if (formula.contains(key)) {
                    formula = formula.replaceAll(key, GlobalVariable.GLOBAL_MAP.get(key).toString());
                }
            }
            Expression expression = new ExpressionBuilder(formula).build();
            double result = expression.evaluate();
            return (float) result;
        } catch (Exception e) {
            for (String key : GlobalVariable.GLOBAL_MAP.keySet()) {
                if (s.contains(key)) {
                    log.warn("key: {}   ----   value: {}", key, GlobalVariable.GLOBAL_MAP.get(key));
                }
            }
            log.error("Formula calculation failed, tableName: {}, origin_formula: {}, new_formula: {}", tableName, s, formula);
        }
        return 1.0f;
    }

}
